#include "widget.h"

RollCall::RollCall(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RollCall)
{
    ui->setupUi(this);   // 初始化UI文件
    setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint);  // 禁用窗口最大化按键
    setFixedSize(this->width(), this->height());  // 固定窗口尺寸

    showUI = new RollCallShow;
    showWinOpen = false;

    nameCallerObj = new nameCaller;
    nameCallerObj->moveToThread(&callerThread);
    connect(&callerThread, &QThread::finished, nameCallerObj, &QObject::deleteLater);
    callerThread.start();

    QTime time = QTime::currentTime();  //获得当前时间
    numRandomGen.seed(time.msec()+time.second()*10000+100);

    clearNumData();

    connect(ui->randNumButton,SIGNAL(clicked()),this,SLOT(genRandNum()));
    connect(ui->clearNumDataButton,SIGNAL(clicked()),this,SLOT(clearNumData()));
    connect(ui->showWinButton,SIGNAL(clicked()),this,SLOT(ctrlShowWin()));
    connect(showUI,SIGNAL(callrollShowClosed()),this,SLOT(showWinClosed()));

    /*------------------随机点名部分-----------------*/
    connect(ui->importButton,SIGNAL(clicked()),this,SLOT(importButtonClicked()));
    connect(this,SIGNAL(selectFile(QString)),nameCallerObj,SLOT(processFile(QString)));
    connect(nameCallerObj,SIGNAL(fileReadResult(bool,QString)),this,SLOT(callerImportResult(bool,QString)));
    connect(nameCallerObj,SIGNAL(callOver()),this,SLOT(callOver()));
    connect(nameCallerObj,SIGNAL(callName(QString)),this,SLOT(callNameShow(QString)));
    connect(ui->startButton,SIGNAL(clicked()),this,SLOT(callBtn()));
    connect(this,SIGNAL(callBtnClicked()),nameCallerObj,SLOT(doCall()));
    connect(ui->nameOnceCheck,SIGNAL(stateChanged(qint32)),nameCallerObj,SLOT(callOnceCheck(qint32)));

#if defined(Q_OS_WIN32)
    desktopPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
#endif

    this->setAcceptDrops(true);   // 开启拖拽文件支持，这里因为默认是发送tab，且初次运行不会产生切换tab事件，所以设置默认开启
}

RollCall::~RollCall()
{
    callerThread.quit();
    callerThread.wait();
    delete showUI;
    delete ui;
}

void RollCall::closeEvent(QCloseEvent *event)
{  // 按下关闭键事件
    qDebug()<<event;
    showUI->close();
    clearNumData();
}

void RollCall::ctrlShowWin(){
    if (showWinOpen){
        closeShowWin();
    }
    else{
        openShowWin();
    }
}

void RollCall::showWinClosed(){
    showWinOpen=false;
    ui->showWinButton->setText(QString("打开扩展窗口"));
}

void RollCall::openShowWin(){
    showUI->show();
    showWinOpen=true;
    ui->showWinButton->setText(QString("关闭扩展窗口"));
}

void RollCall::closeShowWin(){
    showUI->close();
    showWinOpen=false;
    ui->showWinButton->setText(QString("打开扩展窗口"));
}

void RollCall::clearNumData(){
    numSetCheck();
    randNum=1;
    setNum(QString::number(randNum));
    ui->minNumLabel->setText(QString::number(minRandNum));
    ui->maxNumLabel->setText(QString::number(maxRandNum));
    randNumList.clear();
    numListSize = 0;
    for (quint32 tempNum=minRandNum;tempNum<=maxRandNum;tempNum++){
        randNumList.append(tempNum);
        numListSize++;
    }
}

void RollCall::numSetCheck(){
    if ((ui->minNumBox->value())<(ui->maxNumBox->value())){
        ;
    }
    else{
        quint32 maxNum = (ui->maxNumBox->value());
        if (maxNum<=1){
            ui->maxNumBox->setValue(maxNum+1);
            maxNum = (ui->maxNumBox->value());
        }
        ui->minNumBox->setValue(maxNum-1);
    }
    minRandNum = ui->minNumBox->value();
    maxRandNum = ui->maxNumBox->value();
}

void RollCall::genRandNum(){
    if (numListSize>0){
        randNum = numRandomGen.bounded(numListSize);
        setNum(QString::number(randNumList.at(randNum)));
        if (ui->numOnceCheck->isChecked()){
            randNumList.removeAt(randNum);
            numListSize--;
        }
    }
    else{
        setNum("无");
    }
}

/*------------------随机点名部分-----------------*/
void RollCall::dragEnterEvent(QDragEnterEvent *event){
    const QMimeData *mimeData = event->mimeData();
    if (mimeData->hasUrls()){
        QList<QUrl> mimeUrls = mimeData->urls();
        if (mimeUrls.length() == 1){
            QUrl fileUrl = mimeUrls.at(0);
            if (fileUrl.isLocalFile()){
                QString fileName = fileUrl.fileName();
                if ((fileName.mid((fileName.size()-3),3).toLower())==QString("txt")){
                    event->acceptProposedAction();  // 合格文件，接受
                }
                else{
                    event->ignore();
                }
            }
            else{
                event->ignore();
            }
        }
        else{
            qDebug()<<"RollCall::dragEnterEvent - 选择超过一个文件，不接受";
            event->ignore();
        }
    }
    else{
        qDebug()<<"RollCall::dragEnterEvent - 当前拖入对象没有url";
        event->ignore();
    }

}

void RollCall::dropEvent(QDropEvent *event){
    // 拖动文件到窗口释放文件，触发
    // 经测试，只有上面接受了这里才会触发，所以不需要再次判断
    const QMimeData *mimeData = event->mimeData();
    QList<QUrl> mimeUrls = mimeData->urls();
    QUrl fileUrl = mimeUrls.at(0);

    QString filePath = fileUrl.toLocalFile();
    emit selectFile(filePath);
    ui->filePathLabel->setText(filePath);
}

void RollCall::importButtonClicked()
{
    QString filePath;
    filePath = QFileDialog::getOpenFileName(this, QString("选择发送文件"),desktopPath,fileFilter);
    if (filePath.size() > 0){
        emit selectFile(filePath);
        ui->filePathLabel->setText(filePath);
    }
    else{
        QMessageBox::critical(this,"未选择文件","未选择文件",QMessageBox::Ok);
        ui->filePathLabel->setText(filePathLabelDefault);
        ui->startButton->setEnabled(false);
        ui->startButton->setText(startButtonDefault);
        setName(nameLabelDefault);
    }
}

void RollCall::callerImportResult(bool isError, QString msg){
    if (isError){
        if (msg.size() <= 0){
            msg = "未知错误";
        }
        QMessageBox::critical(this,"导入失败",msg,QMessageBox::Ok);
        ui->filePathLabel->setText(filePathLabelDefault);
        ui->startButton->setEnabled(false);
        ui->startButton->setText(startButtonDefault);
        setName(nameLabelDefault);
        callerImported = false;
    }
    else{
        QMessageBox::information(this,"导入成功",msg,QMessageBox::Ok);
        ui->startButton->setEnabled(true);
        ui->startButton->setText(startButtonDefault);
        setName(nameLabelNull);
        callerImported = true;
    }
}

void RollCall::callOver(){
    // setName(nameLabelDefault);
    ui->startButton->setEnabled(false);
    ui->startButton->setText(startButtonDefault);
    ui->filePathLabel->setText(filePathLabelDefault);
    callerImported = false;
}

void RollCall::callNameShow(QString name){
    if (callerImported){
        if (name.size() <= 0){
//            setName(nameLabelNull);
        }
        else{
            setName(name);
        }
    }
    else{
        ;// setName(nameLabelDefault);
    }
}

void RollCall::callBtn(){
    if(callerImported){
        if (nameCalling){
            nameCalling = false;
            ui->startButton->setText(startButtonDefault);
        }
        else{
            nameCalling = true;
            ui->startButton->setText(stopButtonDefault);
        }
        emit callBtnClicked();
    }
    else{
        ui->startButton->setEnabled(false);
        ui->startButton->setText(startButtonDefault);
    }
}


/*------------------ui显示-----------------*/
void RollCall::setName(QString name){
    ui->nameLabel->setText(name);
    showUI->setName(name);
}

void RollCall::setNum(QString num){
    ui->randNumLabel->setText(num);
    showUI->setNum(num);
}
